import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { prisma } from '@/lib/prisma';
import jwt from 'jsonwebtoken';
// import { RefreshTokenRequest } from '@/types/auth';

// POST /api/admin/auth/refresh - 刷新token
async function handlePost(request: NextRequest) {
  const body: { refreshToken: string } = await request.json();
  const { refreshToken } = body;
  if (!refreshToken) {
    throw new Error('刷新token不能为空');
  }

  try {
    // 验证刷新token
    const decoded = jwt.verify(refreshToken, process.env.JWT_SECRET!) as any;
    
    // 查找用户
    const user = await prisma.user.findUnique({
      where: { id: decoded.id }
    });

    if (!user || user.status !== 1) {
      throw new Error('用户不存在或已被禁用');
    }

    // 生成新的访问token
    const accessToken = jwt.sign(
      {
        id: user.id,
        username: user.username,
        role: user.role     
      },
      process.env.JWT_SECRET!,
      { expiresIn: '2h' }
    );

    // 生成新的刷新token
    const newRefreshToken = jwt.sign(
      { id: user.id },
      process.env.JWT_SECRET!,
      { expiresIn: '7d' }
    );

    return {
      accessToken,
      refreshToken: newRefreshToken,
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        avatar: user.avatar,
        role: user.role,
        status: user.status
      }
    };
  } catch (error) {
    throw new Error('刷新token无效或已过期');
  }
}

export const POST = withMiddleware(handlePost);
